import json
import logging
import sys

# from icecream import ic
from openpyxl.drawing.image import Image
# from icecream import ic
import pandas as pd
from openpyxl.styles import Alignment, Font
from openpyxl.styles import PatternFill
from openpyxl import Workbook, load_workbook
from datetime import datetime
from openpyxl.utils import get_column_letter

from gen_df_base import gen_dfs_base
from gen_info_dic import gen_info_dic
from get_sql_res import gen_run_detail
from sheet_cover_page import gen_cover_page
from gen_df_rule_detail import DPAT, SPAT, CORRELATION_RULE
from gen_fig import gen_figs


def write_in_tables(
        re_file_path,
        info_dic,
        df_run_detail,
        sql_info,
        df_run_detail_raw):
    # cover+4个基本sheet+rule_detail
    df_lst, Summary_df, MAP_df, RsRuleSummary_df, RsDieSummary_df = gen_dfs_base(
        df_run_detail, info_dic, sql_info, df_run_detail_raw)

    with pd.ExcelWriter(re_file_path, engine='xlsxwriter') as writer:
        for i, df in enumerate(df_lst):
            df.to_excel(
                writer,
                sheet_name='Cover Page',
                startrow=i * 5,
                index=False,
                header=False)
        Summary_df.to_excel(
            writer,
            sheet_name='Summary',
            startrow=0,
            index=False)
        MAP_df.to_excel(
            writer,
            sheet_name='MAP',
            startrow=0,
            index=False)
        RsRuleSummary_df.to_excel(
            writer,
            sheet_name='RsRuleSummary',
            startrow=0,
            index=False)
        RsDieSummary_df.to_excel(
            writer,
            sheet_name='RsDieSummary',
            startrow=0,
            index=False)
        # 写入rule_detail相关的sheet
        rule_key_alias_mapping = info_dic['rule_map']
        for alias, key in rule_key_alias_mapping.items():
            if key == 'DPAT':
                df = DPAT(df_run_detail)
                df.to_excel(
                    writer,
                    sheet_name=f'{alias} Detail',
                    startrow=1,
                    index=False)
            if key == 'SPAT':
                df = SPAT(df_run_detail)
                df.to_excel(
                    writer,
                    sheet_name=f'{alias} Detail',
                    startrow=1,
                    index=False)
            if key == 'CORRELATION_RULE':
                df = CORRELATION_RULE(df_run_detail)
                df.to_excel(
                    writer,
                    sheet_name=f'{alias} Detail',
                    startrow=1,
                    index=False)


def write_in_figs(path_dic, re_file_path, info_dic):
    loc_info = info_dic['df_info']['MAP']
    existing_wb = load_workbook(re_file_path)
    sheet = existing_wb['MAP']
    for rule_name in info_dic['rule_alias']:
        col_loc = loc_info[rule_name]
        for row_number, row in enumerate(sheet.iter_rows(
                min_col=col_loc, max_col=col_loc), start=1):
            for cell in row:
                if cell.value == 'flag':
                    wafer_id = sheet.cell(row=row_number, column=2).value
                    path = path_dic[wafer_id][rule_name]
                    if path == '':
                        cell.value = ''
                    else:
                        col_letter = get_column_letter(col_loc)
                        # 得到需要插入图片的坐标
                        cell_coordinate = f'{col_letter}{cell.row}'
                        img = Image(path)
                        img.width = 320
                        img.height = 210
                        sheet.add_image(img, cell_coordinate)
    existing_wb.save(re_file_path)


if __name__ == '__main__':
    input = sys.argv[1]
    input = json.loads(input)
    rule_run_record_id = input['recordId']
    sql_info = {}
    sql_info['mysqlInfo'] = input['mysqlInfo']
    sql_info['ckInfo'] = input['ckInfo']
    sql_info['dasHost'] = input['dasHost']
    re_file_path = input['fileFullPath']

    current_time = datetime.now().strftime("%m_%d_%H_%M")
    re_file_path = f"res/file_02_25_22_07.xlsx"
    df_run_detail = gen_run_detail(rule_run_record_id, sql_info)
    info_dic = gen_info_dic(df_run_detail, sql_info)

    ##
    path_dic = {'NT41A_06': {'GDBN': '/home/tom/codes/rule-1159982.png',
                             'Wafer Edge - 2': '/home/tom/codes/rule-1159982.png'},
                'NT41A_08': {'GDBN': '/home/tom/codes/rule-1159982.png',
                             'Wafer Edge - 2': '/home/tom/codes/rule-1159982.png'},
                'NT41A_09': {'Wafer Edge - 2': '/home/tom/codes/rule-1159982.png'},
                'NT41A_10': {'GDBN': '/home/tom/codes/rule-1159982.png',
                             'Wafer Edge - 2': '/home/tom/codes/rule-1159982.png'},
                'NT41A_11': {'GDBN': '/home/tom/codes/rule-1159982.png',
                             'Wafer Edge - 2': '/home/tom/codes/rule-1159982.png'},
                'NT41A_12': {'GDBN': '/home/tom/codes/rule-1159982.png',
                             'Wafer Edge - 2': '/home/tom/codes/rule-1159982.png'},
                'NT41A_13': {'GDBN': '/home/tom/codes/rule-1159982.png',
                             'Wafer Edge - 2': '/home/tom/codes/rule-1159982.png'},
                'NT41A_14': {'GDBN': '/home/tom/codes/rule-1159982.png',
                             'Wafer Edge - 2': '/home/tom/codes/rule-1159982.png'}}
    write_in_figs(path_dic, re_file_path, info_dic)
